#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Drawing;
using System.Collections;
using Widgetsphere.Generator.Common.GeneratorFramework;
using System.Windows.Forms;
using Widgetsphere.Generator.Common.Util;
using System.Xml;
using Widgetsphere.Generator.Forms;

namespace Widgetsphere.Generator.Models
{
	public class TableCompositeCollectionController : BaseModelObjectController
	{
		#region Member Variables

    private ContextMenu PopupMenu = null;
    private ListView ControllerListView = null;

		#endregion

    #region Constructor

    protected internal TableCompositeCollectionController(IModelObject modelObject):base(modelObject)
    {
      System.Diagnostics.Debug.WriteLine("TableCompositeCollectionController:Constructor");
    }

    #endregion

    #region BaseModelObjectController Members

    public override ModelObjectTreeNode Node
		{
			get
			{
				if(_node == null)
				{
					_node = new TableCompositeCollectionNode(this);
				}
				return _node;
			}
		}

		public override ModelObjectUserInterface UIControl
		{
			get
			{
				if(this.UserInterface == null)
				{
					PanelUIControl ctrl = new PanelUIControl();
          ControllerListView = new ListView();
					ControllerListView.View = View.Details;
          ControllerListView.HideSelection = false;
          ControllerListView.FullRowSelect = true;
          ControllerListView.Dock = DockStyle.Fill;
          ControllerListView.Columns.Add("Name", 250, HorizontalAlignment.Left);
          System.Type[] typeList = new System.Type[] { typeof(string), typeof(string), typeof(int) };
          Widgetsphere.Generator.Common.Forms.ListViewComparer comparer = new Widgetsphere.Generator.Common.Forms.ListViewComparer(ControllerListView, typeList);
          ControllerListView.ListViewItemSorter = comparer;
          comparer.Column = 0;
          ControllerListView.Sorting = SortOrder.Ascending;
          ControllerListView.SmallImageList = Widgetsphere.Generator.ImageHelper.GetImageList();
					ctrl.MainPanel.Controls.Add(ControllerListView);
					ctrl.Dock = DockStyle.Fill;          

          ControllerListView.MouseUp += new MouseEventHandler(listView_MouseUp);
          ControllerListView.KeyUp += new KeyEventHandler(listView_KeyUp);
          ControllerListView.DoubleClick += new EventHandler(listView_DoubleClick);

          PopupMenu = new ContextMenu();
          ControllerListView.ContextMenu = PopupMenu;
          MenuItem menuDelete = new MenuItem("Delete");
          menuDelete.Click += new EventHandler(menuDelete_Click);
          PopupMenu.MenuItems.Add(menuDelete);

					this.UserInterface = ctrl;
				}

				//Load the list
				ControllerListView.Items.Clear();
				foreach (TableComposite composite in (TableCompositeCollection)this.Object)
				{
					ListViewItem newItem = new ListViewItem(composite.Name);
					newItem.Tag = composite;
					newItem.Name = composite.Key;
					ControllerListView.Items.Add(newItem);
				}

				ControllerListView.Sort();

				return this.UserInterface;
			}
		}

    private void listView_DoubleClick(object sender, System.EventArgs e)
    {
    }

    private void listView_KeyUp(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Delete)
      {
        menuDelete_Click(null, null);
      }
    }

    private void listView_MouseUp(object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Right)
      {
        PopupMenu.Show((ListView)sender, new Point(e.X, e.Y));
      }
    }

    private void menuDelete_Click(object sender, System.EventArgs e)
    {
			if (MessageBox.Show("Do you wish to delete the selected composites?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
        return;

      foreach(ListViewItem item in ControllerListView.SelectedItems)
        ((TableCompositeCollection)this.Object).Remove((TableComposite)item.Tag);

      //Remove the item from the listview
      for(int ii = ControllerListView.SelectedItems.Count - 1 ; ii >= 0 ; ii--)
      {
        //Remove the item from the tree
        this.Node.Nodes.Remove(this.Node.Nodes[ControllerListView.SelectedItems[ii].Name]);
        //Remove Listitem
        ControllerListView.Items.Remove(ControllerListView.SelectedItems[ii]);
      }

      this.Object.Root.Dirty = true;

    }
    
    public override MenuCommand[] GetMenuCommands()
		{
			MenuCommand mcAddComposite = new DefaultMenuCommand();
			mcAddComposite.Text = "New Composite";
			mcAddComposite.Click += new EventHandler(AddMenuCompositeClick);

			MenuCommand mcAddComponent = new DefaultMenuCommand();
			mcAddComponent.Text = "New Component";
			mcAddComponent.Click += new EventHandler(AddMenuComponentClick);

			return new MenuCommand[] { mcAddComposite, mcAddComponent };
		}

    public override MessageCollection Verify()
    {
      try
      {
        MessageCollection retval = new MessageCollection();
        retval.AddRange(base.Verify());

				TableCompositeCollection tableCompositeCollection = (TableCompositeCollection)this.Object;

        //Check for duplicate names
        Hashtable nameList = new Hashtable();
				foreach (TableComposite composite in tableCompositeCollection)
				{
					string name = composite.Name.ToLower();
					if (nameList.ContainsKey(name))
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextDuplicateName, composite.Name), this);
					else
						nameList.Add(name, "");
				}

				foreach (TableComposite composite in tableCompositeCollection)
				{
					if (composite.Columns.Count == 0)
					{
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTableCompositeNoColumns, composite.Name), this);
					}
				}

        return retval;

      }
      catch (Exception ex)
      {
        throw;
      }

    }

    public override bool DeleteObject()
    {
      return false;
    }

    public override void Refresh()
    {
      this.UserInterface = null;
    }

		#endregion

		#region Menu Handlers

		private void UpdateCodefacadeColumnMenuClick(object sender, System.EventArgs e)
		{
			ColumnCodeFacadeUpdateForm F = new ColumnCodeFacadeUpdateForm(null, (ModelRoot)((TableCompositeCollection)this.Object).Root, ColumnCodeFacadeUpdateForm.FieldSettingConstants.CodeFacade);
			F.ShowDialog();
		}

		private void UpdateColumnNameColumnMenuClick(object sender, System.EventArgs e)
		{
			ColumnCodeFacadeUpdateForm F = new ColumnCodeFacadeUpdateForm(null, (ModelRoot)((TableCompositeCollection)this.Object).Root, ColumnCodeFacadeUpdateForm.FieldSettingConstants.Name);
			F.ShowDialog();
		}

		private void AddMenuCompositeClick(object sender, System.EventArgs e)
		{
			TableCompositeCollection collection = (TableCompositeCollection)this.Object;
			TableComposite newItem = collection.Add(new TableComposite(collection.Root, collection.Parent));
			newItem.Name = "[NEW COMPOSITE]";
			this.OnItemChanged(this, new System.EventArgs());
		}

		private void AddMenuComponentClick(object sender, System.EventArgs e)
		{
			TableComponentCollection collection = (TableComponentCollection)this.Object;
			TableComponent newItem = collection.Add(new TableComponent(collection.Root, collection.Parent));
			newItem.Name = "[NEW COMPONENT]";
			this.OnItemChanged(this, new System.EventArgs());
		}

		#endregion

	}
}